import 'package:flutter/material.dart';
import '../../models/post_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import '../../widgets/rich_text_display.dart';
import '../comment/comment_page.dart';
import 'package:base_flutter/src/network/network_exception.dart';

/// 图文动态详情页面
/// 显示图文动态的完整内容，包括图片、文字、互动功能等
class PostDetailPage extends StatefulWidget {
  final PostModel post;

  const PostDetailPage({
    super.key,
    required this.post,
  });

  @override
  State<PostDetailPage> createState() => _PostDetailPageState();
}

class _PostDetailPageState extends State<PostDetailPage> {
  PostModel? _postDetail;
  bool _isLoading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadPostDetail();
  }

  /// 加载动态详情
  Future<void> _loadPostDetail() async {
    try {
      setState(() {
        _isLoading = true;
        _error = null;
      });

      final postDetail = await ApiService().getPostDetail(widget.post.id);
      
      setState(() {
        _postDetail = postDetail;
        _isLoading = false;
      });

      Logger.d('POST_DETAIL', '动态详情加载成功');
    } catch (e) {
      Logger.e('POST_DETAIL', '动态详情加载失败: $e');
      setState(() {
        _error = e is NetworkException ? e.message : '加载失败';
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('动态详情'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: _handleShare,
          ),
          IconButton(
            icon: const Icon(Icons.more_vert),
            onPressed: _showMoreOptions,
          ),
        ],
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              _error!,
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadPostDetail,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    final post = _postDetail ?? widget.post;

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 作者信息
          _buildAuthorInfo(post),
          const SizedBox(height: 16),
          
          // 动态内容
          _buildPostContent(post),
          const SizedBox(height: 16),
          
          // 图片展示
          if (post.coverUrl != null && post.coverUrl!.isNotEmpty) ...[
            _buildCoverImage(post.coverUrl!),
            const SizedBox(height: 16),
          ] else if (post.images.isNotEmpty) ...[
            _buildImageGallery(post.images),
            const SizedBox(height: 16),
          ],
          
          // 技能标签
          if (post.skillTags.isNotEmpty) ...[
            _buildSkillTags(post.skillTags),
            const SizedBox(height: 16),
          ],
          
          // 互动区域
          _buildInteractionArea(post),
          const SizedBox(height: 24),
          
          // 评论区域
          _buildCommentsSection(),
        ],
      ),
    );
  }

  /// 构建作者信息
  Widget _buildAuthorInfo(PostModel post) {
    return Row(
      children: [
        CachedAvatarWidget(
          avatarUrl: post.userAvatar,
          size: 48,
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    post.username,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  if (post.isHot) ...[
                    const SizedBox(width: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: const Text(
                        '热门',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ],
              ),
              const SizedBox(height: 4),
              Row(
                children: [
                  Icon(
                    Icons.location_on,
                    size: 14,
                    color: Colors.grey[600],
                  ),
                  const SizedBox(width: 4),
                  Text(
                    post.location ?? '',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    _getTimeAgo(post.createdAt),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        ElevatedButton(
          onPressed: _handleFollow,
          child: const Text('关注'),
        ),
      ],
    );
  }

  /// 构建动态内容
  Widget _buildPostContent(PostModel post) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildContentDisplay(post.content),
          if (post.summary != null && post.summary!.isNotEmpty) ...[
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.grey[200]!),
              ),
              child: Text(
                post.summary!,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[700],
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建封面图片
  Widget _buildCoverImage(String coverUrl) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: CachedImageWidget(
        imageUrl: coverUrl,
        width: double.infinity,
        height: 300,
        fit: BoxFit.cover,
        borderRadius: BorderRadius.circular(8),
        imageType: '详情页封面',
        errorWidget: Container(
          height: 300,
          color: Colors.grey[200],
          child: const Icon(Icons.image_not_supported, size: 50),
        ),
      ),
    );
  }

  /// 构建图片画廊
  Widget _buildImageGallery(List<String> images) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Icon(Icons.photo_library, size: 20),
                const SizedBox(width: 8),
                Text(
                  '图片 (${images.length})',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
            child: _buildImageGrid(images),
          ),
        ],
      ),
    );
  }

  /// 构建图片网格
  Widget _buildImageGrid(List<String> images) {
    if (images.length == 1) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Image.network(
          images[0],
          width: double.infinity,
          height: 300,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              height: 300,
              color: Colors.grey[200],
              child: const Icon(Icons.image_not_supported, size: 50),
            );
          },
        ),
      );
    } else if (images.length == 2) {
      return Row(
        children: [
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.network(
                images[0],
                height: 200,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    height: 200,
                    color: Colors.grey[200],
                    child: const Icon(Icons.image_not_supported, size: 30),
                  );
                },
              ),
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.network(
                images[1],
                height: 200,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    height: 200,
                    color: Colors.grey[200],
                    child: const Icon(Icons.image_not_supported, size: 30),
                  );
                },
              ),
            ),
          ),
        ],
      );
    } else {
      return GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
        ),
        itemCount: images.length > 9 ? 9 : images.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () => _showImagePreview(images, index),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Stack(
                fit: StackFit.expand,
                children: [
                  Image.network(
                    images[index],
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: Colors.grey[200],
                        child: const Icon(Icons.image_not_supported, size: 20),
                      );
                    },
                  ),
                  if (index == 8 && images.length > 9)
                    Container(
                      color: Colors.black.withOpacity(0.5),
                      child: Center(
                        child: Text(
                          '+${images.length - 9}',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          );
        },
      );
    }
  }

  /// 显示图片预览
  void _showImagePreview(List<String> images, int initialIndex) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ImagePreviewPage(
          images: images,
          initialIndex: initialIndex,
        ),
      ),
    );
  }

  /// 构建技能标签
  Widget _buildSkillTags(List<String> skillTags) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '相关标签',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: skillTags.map((tag) {
              return Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(16),
                  border: Border.all(
                    color: Theme.of(context).primaryColor.withOpacity(0.3),
                  ),
                ),
                child: Text(
                  tag,
                  style: TextStyle(
                    color: Theme.of(context).primaryColor,
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  /// 构建互动区域
  Widget _buildInteractionArea(PostModel post) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildInteractionButton(
            icon: post.isLiked ? Icons.favorite : Icons.favorite_border,
            label: '${post.likesCount}',
            color: post.isLiked ? Colors.red : Colors.grey[600],
            onTap: () => _handleLike(post),
          ),
          _buildInteractionButton(
            icon: Icons.comment,
            label: '${post.commentsCount}',
            color: Colors.grey[600],
            onTap: () => _navigateToComments(post),
          ),
          _buildInteractionButton(
            icon: Icons.share,
            label: '${post.sharesCount}',
            color: Colors.grey[600],
            onTap: _handleShare,
          ),
          _buildInteractionButton(
            icon: Icons.visibility,
            label: '${post.viewsCount}',
            color: Colors.grey[600],
            onTap: () {},
          ),
        ],
      ),
    );
  }

  /// 构建互动按钮
  Widget _buildInteractionButton({
    required IconData icon,
    required String label,
    required Color? color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Icon(
            icon,
            color: color,
            size: 24,
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              color: color,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建评论区域
  Widget _buildCommentsSection() {
    final post = _postDetail ?? widget.post;
    
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '评论 (${post.commentsCount})',
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          TextButton(
            onPressed: () => _navigateToComments(post),
            child: const Text('查看全部'),
          ),
        ],
      ),
    );
  }


  /// 处理点赞
  void _handleLike(PostModel post) async {
    try {
      await ApiService().likePost(post.id, !post.isLiked);
      
      setState(() {
        if (_postDetail != null) {
          _postDetail = _postDetail!.copyWith(
            isLiked: !post.isLiked,
            likesCount: post.isLiked ? post.likesCount - 1 : post.likesCount + 1,
          );
        }
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(!post.isLiked ? '已点赞' : '已取消点赞'),
        ),
      );
    } catch (e) {
      Logger.e('POST_DETAIL', '点赞失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 跳转到评论页面
  void _navigateToComments(PostModel post) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CommentPage(
          postId: post.id,
          postTitle: post.title ?? '动态详情',
          initialCommentsCount: post.commentsCount,
        ),
      ),
    ).then((_) {
      // 从评论页面返回后，刷新详情页的评论数
      _loadPostDetail();
    });
  }

  /// 处理评论（已废弃，现在直接跳转到评论页面）
  void _handleComment() {
    _navigateToComments(_postDetail ?? widget.post);
  }

  /// 处理分享
  void _handleShare() async {
    try {
      await ApiService().sharePost(widget.post.id);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('分享成功')),
      );
    } catch (e) {
      Logger.e('POST_DETAIL', '分享失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('分享失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理关注
  void _handleFollow() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('关注功能开发中...')),
    );
  }

  /// 显示更多选项
  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.bookmark_border),
              title: const Text('收藏'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('收藏功能开发中...')),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 获取时间差
  String _getTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  /// 构建内容显示组件
  /// 处理富文本编辑器生成的内容，支持图片显示
  Widget _buildContentDisplay(String content) {
    if (content.isEmpty) {
      return const SizedBox.shrink();
    }

    // 使用 SimpleRichTextDisplay 来正确显示富文本内容，包括图片
    return SimpleRichTextDisplay(
      content: content,
      textStyle: const TextStyle(
        fontSize: 16,
        height: 1.5,
      ),
    );
  }
}

/// 图片预览页面
class ImagePreviewPage extends StatefulWidget {
  final List<String> images;
  final int initialIndex;

  const ImagePreviewPage({
    super.key,
    required this.images,
    this.initialIndex = 0,
  });

  @override
  State<ImagePreviewPage> createState() => _ImagePreviewPageState();
}

class _ImagePreviewPageState extends State<ImagePreviewPage> {
  late PageController _pageController;
  late int _currentIndex;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: widget.initialIndex);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        foregroundColor: Colors.white,
        elevation: 0,
        title: Text('${_currentIndex + 1} / ${widget.images.length}'),
      ),
      body: PageView.builder(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        itemCount: widget.images.length,
        itemBuilder: (context, index) {
          return Center(
            child: InteractiveViewer(
              child: Image.network(
                widget.images[index],
                fit: BoxFit.contain,
                errorBuilder: (context, error, stackTrace) {
                  return const Icon(
                    Icons.image_not_supported,
                    color: Colors.white,
                    size: 100,
                  );
                },
              ),
            ),
          );
        },
      ),
    );
  }
}





